package com.buster.dumbshellarts;

import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.Cursor;
import android.database.SQLException;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.GestureDetector;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MainActivity extends Activity implements OnGestureListener,
		OnDoubleTapListener {

	TextView movieTitle, actors, director, year, yearLabel, directorLabel,
			actorsLabel;
	TextView timerText, group1Score, group2Score, group1Title, group2Title;
	ToggleButton timerToggle;
	DBHelper myDBHelper = new DBHelper(this);
	Button next, help;
	String timerSpan;
	MediaPlayer timerTick, failBuzzer;
	private GestureDetector detector;
	// private Decades decades = new Decades();
	private OnSharedPreferenceChangeListener listener;
	private boolean callActivated;

	// int group1, group2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		detector = new GestureDetector(this, this);

		timerTick = MediaPlayer.create(getApplicationContext(), R.raw.timer);
		failBuzzer = MediaPlayer.create(getApplicationContext(),
				R.raw.failbuzzer);

		try {
			myDBHelper.createDataBase();
		} catch (IOException ioe) {
			throw new Error("Unable to create database");
		}
		try {
			myDBHelper.openDataBase();
		} catch (SQLException sqle) {
			throw sqle;
		}

		listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
			@Override
			public void onSharedPreferenceChanged(SharedPreferences prefs,
					String key) {
				populateMovie();
				setTimerVisibility();
			}
		};

		movieTitle = (TextView) findViewById(R.id.movieTitleLarge);
		actors = (TextView) findViewById(R.id.actors);
		actorsLabel = (TextView) findViewById(R.id.actorsLabel);
		director = (TextView) findViewById(R.id.director);
		directorLabel = (TextView) findViewById(R.id.directorLabel);
		year = (TextView) findViewById(R.id.year);
		yearLabel = (TextView) findViewById(R.id.yearLabel);

		timerText = (TextView) findViewById(R.id.timer);
		group1Score = (TextView) findViewById(R.id.group1Score);
		group2Score = (TextView) findViewById(R.id.group2Score);
		group1Title = (TextView) findViewById(R.id.group1Title);
		group2Title = (TextView) findViewById(R.id.group2Title);
		group1Score.setVisibility(View.GONE);
		group2Score.setVisibility(View.GONE);
		group1Title.setVisibility(View.GONE);
		group2Title.setVisibility(View.GONE);

		actors.setTextColor(Color.WHITE);
		director.setTextColor(Color.WHITE);
		year.setTextColor(Color.WHITE);
		year.setTextColor(Color.WHITE);
		timerText.setTextColor(Color.WHITE);
		actorsLabel.setTextColor(Color.WHITE);
		directorLabel.setTextColor(Color.WHITE);
		yearLabel.setTextColor(Color.WHITE);

		populateMovie();

		next = (Button) findViewById(R.id.nextButton);
		next.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				populateMovie();
			}
		});

		help = (Button) findViewById(R.id.helpButton);
		help.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(MainActivity.this, HelpActivity.class));
			}
		});

		timerToggle = (ToggleButton) findViewById(R.id.timerToggle);
		timerToggle.setOnClickListener(new View.OnClickListener() {
			private boolean running = false;
			private CountDownTimer countTimer;

			@Override
			public void onClick(View v) {
				if (!running) {
					running = true;
					int time = Integer.parseInt(getTimeSpan() + "000");
					countTimer = new CountDownTimer(time, 1000) {
						@Override
						public void onFinish() {
							timerText.setText("Done!");
							timerToggle.setChecked(false);
							timerToggle.setText("Start");
							if (!callActivated)
								failBuzzer.start();
							running = false;
						}

						@Override
						public void onTick(long sec) {
							timerText.setText("Left: " + sec / 1000);
							if (sec / 1000 <= 10 && !callActivated) {
								timerTick.start();
							}
						}
					}.start();
				} else {
					countTimer.cancel();
					timerText.setText("00");
					running = false;
				}
			}
		});

		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(MainActivity.this);
		prefs.registerOnSharedPreferenceChangeListener(listener);
		if (prefs.getString("timeSpan", null) == null) {
			startActivity(new Intent(this, PrefsActivity.class));
			return;
		}

		setTimerVisibility();

		PhoneStateListener phoneStateListener = new PhoneStateListener() {
			@Override
			public void onCallStateChanged(int state, String incomingNumber) {
				if (state == TelephonyManager.CALL_STATE_RINGING) {
					// INCOMING call
					/*
					 * if (timerTick != null) { if (timerTick.isPlaying())
					 * timerTick.stop(); }
					 */callActivated = true;
				} else if (state == TelephonyManager.CALL_STATE_IDLE) {
					// Not IN CALL
					callActivated = false;
				} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
					// A call is dialing, active or on hold

					/*
					 * if (timerTick != null) { if (timerTick.isPlaying())
					 * timerTick.stop(); }
					 */callActivated = true;
				}
				super.onCallStateChanged(state, incomingNumber);
			}
		};

		TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		if (mgr != null) {
			mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.settings_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case R.id.settingsItem:
			startActivity(new Intent(MainActivity.this, PrefsActivity.class));
			break;

		case R.id.exitItem:
			if (timerTick.isPlaying())
				timerTick.stop();
			if (failBuzzer.isPlaying())
				failBuzzer.stop();
			if (myDBHelper.isDataBaseOpen())
				myDBHelper.close();
			this.finish();
			break;
		}
		return true;
	}

	private String getSelectedLanguage() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(MainActivity.this);
		// prefs.registerOnSharedPreferenceChangeListener(listener);

		String language = prefs.getString("language", "0");
		return language;
	}

	private void setTimerVisibility() {
		boolean val = getTimerVisibility();
		if (val) {
			timerToggle.setVisibility(View.VISIBLE);
			timerText.setVisibility(View.VISIBLE);
			/*
			 * group1Title.setVisibility(View.VISIBLE);
			 * group2Title.setVisibility(View.VISIBLE);
			 * group1Score.setVisibility(View.VISIBLE);
			 * group2Score.setVisibility(View.VISIBLE);
			 */
		} else {
			timerToggle.setVisibility(View.GONE);
			timerText.setVisibility(View.GONE);
			/*
			 * group1Title.setVisibility(View.GONE);
			 * group2Title.setVisibility(View.GONE);
			 * group1Score.setVisibility(View.GONE);
			 * group2Score.setVisibility(View.GONE);
			 */
		}
	}

	private boolean getTimerVisibility() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(MainActivity.this);
		return prefs.getBoolean(getString(R.string.showTimerKey), false);
	}

	/*
	 * private Decades getSelectedDecades() { SharedPreferences prefs =
	 * PreferenceManager .getDefaultSharedPreferences(MainActivity.this);
	 * 
	 * Decades decades = new Decades();
	 * 
	 * decades.setChkAll(prefs.getBoolean(getString(R.string.chkAllKey), true));
	 * decades.setChk1930s(prefs.getBoolean(getString(R.string.chk1930sKey),
	 * true));
	 * decades.setChk1940s(prefs.getBoolean(getString(R.string.chk1940sKey),
	 * true));
	 * decades.setChk1950s(prefs.getBoolean(getString(R.string.chk1950sKey),
	 * true));
	 * decades.setChk1960s(prefs.getBoolean(getString(R.string.chk1960sKey),
	 * true));
	 * decades.setChk1970s(prefs.getBoolean(getString(R.string.chk1970sKey),
	 * true));
	 * decades.setChk1980s(prefs.getBoolean(getString(R.string.chk1980sKey),
	 * true));
	 * decades.setChk1990s(prefs.getBoolean(getString(R.string.chk1990sKey),
	 * true));
	 * decades.setChk2000s(prefs.getBoolean(getString(R.string.chk2000sKey),
	 * true));
	 * decades.setChk2010s(prefs.getBoolean(getString(R.string.chk2010sKey),
	 * true));
	 * 
	 * return decades; }
	 */

	private String getTimeSpan() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(MainActivity.this);

		String time = prefs.getString("timeSpan", "30");
		return time;
	}

	private void SetMovieTitle(Cursor cursor) {
		if (cursor != null) {
			String title = cursor.getString(cursor
					.getColumnIndex(DBHelper.COL_TITLE));
			String URL = cursor.getString(cursor
					.getColumnIndex(DBHelper.COL_URL));

			movieTitle.setText(Html.fromHtml("<a href=" + URL + ">" + title
					+ "</a> "));
			movieTitle.setMovementMethod(LinkMovementMethod.getInstance());

			actors.setText(cursor.getString(cursor
					.getColumnIndex(DBHelper.COL_ACTORS)));
			director.setText(cursor.getString(cursor
					.getColumnIndex(DBHelper.COL_DIRECTOR)));
			year.setText(cursor.getString(cursor
					.getColumnIndex(DBHelper.COL_YEAR)));
		}
	}

	private void populateMovie() {
		/*
		 * decades = this.getSelectedDecades(); if
		 * (decades.isAtLeastOneDecadeSelected()) { if
		 * (getSelectedLanguage().equals("0") && decades.isChkAll()) { Cursor
		 * cursor = myDBHelper.getRandomMovie(); SetMovieTitle(cursor);
		 * cursor.close(); } if (decades.isChkAll() &&
		 * !getSelectedLanguage().equals("0")) { Cursor cursor =
		 * myDBHelper.getRandomMovieByLanguage(Integer
		 * .parseInt(getSelectedLanguage())); SetMovieTitle(cursor);
		 * cursor.close(); } if (!decades.isChkAll()) { if
		 * (getSelectedLanguage().equals("0")) { Cursor cursor =
		 * myDBHelper.getRandomMovieByDecades( decades.isChk1930s(),
		 * decades.isChk1940s(), decades.isChk1950s(), decades.isChk1960s(),
		 * decades.isChk1970s(), decades.isChk1980s(), decades.isChk1990s(),
		 * decades.isChk2000s(), decades.isChk2010s()); SetMovieTitle(cursor);
		 * cursor.close(); } else { Cursor cursor = myDBHelper
		 * .getRandomMovieByLanguageAndDecades(
		 * Integer.parseInt(getSelectedLanguage()), decades.isChk1930s(),
		 * decades.isChk1940s(), decades.isChk1950s(), decades.isChk1960s(),
		 * decades.isChk1970s(), decades.isChk1980s(), decades.isChk1990s(),
		 * decades.isChk2000s(), decades.isChk2010s()); SetMovieTitle(cursor);
		 * cursor.close();
		 * 
		 * } } }
		 */
		if (getSelectedLanguage().equals("0")) {
			Cursor cursor = myDBHelper.getRandomMovie();
			SetMovieTitle(cursor);
			cursor.close();
		} else {
			Cursor cursor = myDBHelper.getRandomMovieByLanguage(Integer
					.parseInt(getSelectedLanguage()));
			SetMovieTitle(cursor);
			cursor.close();
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent me) {
		this.detector.onTouchEvent(me);
		return super.onTouchEvent(me);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		// Log.d("---onDown----", e.toString());
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// Log.d("---onFling---", e1.toString() + e2.toString());
		// populateMovie();
		final float xDistance = Math.abs(e1.getX() - e2.getX());
		final float yDistance = Math.abs(e1.getY() - e2.getY());

		if (xDistance > 550)// || yDistance > 350)
			return false;

		velocityX = Math.abs(velocityX);
		velocityY = Math.abs(velocityY);
		boolean result = false;

		if (velocityX > 100 && xDistance > 100) {
			if (e1.getX() > e2.getX()) {// right to left
				// this.listener.onSwipe(SWIPE_LEFT);
				populateMovie();
			} else {
				// this.listener.onSwipe(SWIPE_RIGHT);
			}

			result = true;
		} else if (velocityY > 100 && yDistance > 100) {
			if (e1.getY() > e2.getY()) { // bottom to up
				// this.listener.onSwipe(SWIPE_UP);
			} else {
				// this.listener.onSwipe(SWIPE_DOWN);
			}

			result = true;
		}

		return result;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// Log.d("---onLongPress---", e.toString());
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// Log.d("---onScroll---", e1.toString() + e2.toString());
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// Log.d("---onShowPress---", e.toString());
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// Log.d("---onSingleTapUp---", e.toString());
		return false;
	}

	@Override
	public boolean onDoubleTap(MotionEvent e) {
		// Log.d("---onDoubleTap---", e.toString());
		populateMovie();
		return false;
	}

	@Override
	public boolean onDoubleTapEvent(MotionEvent e) {
		// Log.d("---onDoubleTapEvent---", e.toString());
		return false;
	}

	@Override
	public boolean onSingleTapConfirmed(MotionEvent e) {
		// Log.d("---onSingleTapConfirmed---", e.toString());
		return false;
	}
}
